<template>
  <div>
    <el-container>
      <el-main>
        <el-header class="header-class" height="22">
          <div class="header-text">Function Maintenance</div>
        </el-header>
        <div class="panel-border">
          <el-row>
            <div class="add-button-class">
              <el-button @click="onAddFunctionBtn">Add Function</el-button>
            </div>
          </el-row>
          <el-table border class="table" :data="functionTableData" style="width: 98%" :size="tableSize"
                    @row-click="onFunctionTableRowClick" empty-text="No record found" :highlight-current-row=true>
            <el-table-column label="#" type="index">
              <template slot-scope="scope">
                {{(functionCurrentPage - 1) * functionPagable.limit + scope.$index + 1}}
              </template>
            </el-table-column>
            <el-table-column label="Function Name" prop="functionName">
            </el-table-column>
            <el-table-column label="Function Description" prop="functionDesc">
            </el-table-column>
            <el-table-column label="Status Related" prop="statusRelated">
              <template slot-scope="scope">
                <el-checkbox v-model="functionTableData[scope.$index].statusRelated" disabled></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="Role Related" prop="roleRelated">
              <template slot-scope="scope">
                <el-checkbox v-model="functionTableData[scope.$index].roleRelated" disabled></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="Active" prop="active">
              <template slot-scope="scope">
                <el-checkbox v-model="functionTableData[scope.$index].active" disabled></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="Action">
              <template slot-scope="scope">
                <el-button size="mini" @click="handleEditFunctionListButton(scope.$index, scope.row)"
                           icon="el-icon-edit">
                  Edit
                </el-button>
                <el-button size="mini" type="danger"
                           @click="handleDeleteFunctionListButton(scope.$index, scope.row)"
                           icon="el-icon-delete">
                  Delete
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-container>
            <div class="pagination">
              <el-pagination layout="prev, pager, next" :total="functionPagable.totalElements"
                             :page-size="functionPagable.limit"
                             @current-change="onFunctionListPageChange" :current-page="functionCurrentPage">
              </el-pagination>
            </div>
          </el-container>
        </div>
      </el-main>
    </el-container>

    <el-container>
      <el-main>
        <el-header class="header-class" height="22">
          <div class="header-text">Function Authorization Maintenance</div>
        </el-header>
        <div class="panel-border">
          <el-row>
            <div class="add-button-class">
              <el-button @click="onAddFunctionAuthBtn"
                         v-show="this.isSelectedFunction&&(this.currentFunctionRoleRelated||this.currentFunctionStatusRelated)">
                Add Authorization
              </el-button>
            </div>
          </el-row>
          <el-table border class="table" :data="functionAuthorizationTableData" style="width: 98%" :size="tableSize"
                    empty-text="No record found">
            <el-table-column label="#" type="index">
            </el-table-column>
            <el-table-column label="Function Name" prop="functionName">
            </el-table-column>
            <el-table-column label="Status" prop="statusName">
            </el-table-column>
            <el-table-column label="Role" prop="roleName">
            </el-table-column>
            <el-table-column label="Action">
              <template slot-scope="scope">
                <el-button size="mini" type="danger"
                           @click="handleDeleteFunctionAuthButton(scope.$index, scope.row)"
                           icon="el-icon-delete">
                  Delete
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-main>
    </el-container>

    <!--Edit Function Dialog-->
    <el-dialog class="dialog" :visible="editFunctionListDialogVisible" width="30%" :show-close="false" center>
      <function-list-edit-form ref="editFunctionListDialogForm"></function-list-edit-form>
      <span slot="footer" class="dialog-footer">
            <el-button type="primary" v-show="isAddFunction" @click="addNewFunction">Add</el-button>
            <el-button type="primary" v-show="!isAddFunction" @click="onEditFunctionListSaveBtn">Save</el-button>
            <el-button @click="onEditFunctionListCancelBtn">Cancel</el-button>
          </span>
    </el-dialog>
    <!--Edit Function Auth Dialog-->
    <el-dialog
      class="dialog"
      :visible="editFunctionAuthDialogVisible"
      width="80%" :show-close="false" center>
      <function-auth-edit-form ref="editFunctionAuthDialogForm"></function-auth-edit-form>
      <span slot="footer" class="dialog-footer">
              <el-button type="primary" @click="onEditFunctionAuthSaveBtn">Save</el-button>
              <el-button @click="onEditFunctionAuthCancelBtn">Cancel</el-button>
            </span>
    </el-dialog>
  </div>
</template>

<script>
import functionListEditForm from './FunctionListEditForm.vue'
import functionListAuthorizationService from '@/service/functionListAuthorization'
import functionAuthEditForm from './FunctionAuthEditForm'
import statusService from '@/service/status'
import rolesService from '@/service/role'
import util from '@/common/js/util'

const FIRST_PAGE_NUMBER = 1
const OVER_ALL = 'OverAll'
export default {
  components: {
    functionListEditForm,
    functionAuthEditForm
  },
  data() {
    return {
      tableSize: 'mini',
      isAddFunction: false,
      editFunctionListDialogVisible: false,
      editFunctionAuthDialogVisible: false,
      selectedFunctionId: '',
      functionCurrentPage: FIRST_PAGE_NUMBER,
      functionPagable: {
        totalElements: 0,
        limit: 5
      },
      functionAuthorizationTableData: [],
      functionTableData: [],
      currentFunctionObj: {},
      isSelectedFunction: false,
      currentFunctionRoleRelated: false,
      currentFunctionStatusRelated: false,
      statusList: [],
      rolesList: []
    }
  },
  mounted() {
    this.getFunctionList(FIRST_PAGE_NUMBER)
    this.getOverAllStatus()
    this.getAllRoles()
  },
  methods: {
    resetFunctionList() {
      this.getFunctionList(FIRST_PAGE_NUMBER)
      this.functionAuthorizationTableData = []
    },
    // function maintenance
    onAddFunctionBtn() {
      this.editFunctionListDialogVisible = true
      this.isAddFunction = true
      let defaultFunctionAuthorizationTableData = {
        functionName: '',
        functionDesc: '',
        statusRelated: true,
        roleRelated: true,
        active: true
      }
      this.$nextTick(() => {
        this.$refs.editFunctionListDialogForm.setFunctionListEditModel(defaultFunctionAuthorizationTableData)
      })
    },
    addNewFunction() {
      this.$refs.editFunctionListDialogForm.validateForm().then(async (valid) => {
        if (valid) {
          let newFunction = this.$refs.editFunctionListDialogForm.getFunctionListEditModel()
          await functionListAuthorizationService.addFunction(newFunction)
          this.editFunctionListDialogVisible = false
          this.resetFunctionList()
        }
      })
    },
    handleEditFunctionListButton(index, rowObject) {
      let tempObject = util.deepClone(rowObject)
      this.setDataToFunctionListForm(tempObject)
    },
    onEditFunctionListSaveBtn() {
      this.$refs.editFunctionListDialogForm.validateForm().then(async (valid) => {
        if (valid) {
          let func = this.$refs.editFunctionListDialogForm.getFunctionListEditModel()
          await functionListAuthorizationService.updateFunction(func)
          this.editFunctionListDialogVisible = false
          this.resetFunctionList()
        }
      })
    },
    setDataToFunctionListForm(rowObject) {
      this.isAddFunction = false
      this.editFunctionListDialogVisible = true
      this.$nextTick(() => {
        this.$refs.editFunctionListDialogForm.setFunctionListEditModel(rowObject)
      })
    },
    onFunctionTableRowClick(functionObj) {
      this.isSelectedFunction = true
      this.currentFunctionStatusRelated = functionObj.statusRelated
      this.currentFunctionRoleRelated = functionObj.roleRelated
      this.currentFunctionObj = functionObj
      this.getFunctionAuthorization(functionObj.id)
    },
    onFunctionListPageChange(page) {
      this.getFunctionList(page)
    },
    onEditFunctionListCancelBtn() {
      this.editFunctionListDialogVisible = false
    },
    handleDeleteFunctionListButton(index, row) {
      this.$confirm(`Are you sure you want to delete this Function ?`, 'Warning', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: 'Delete',
        cancelButtonText: 'Cancel',
        type: 'warning',
        callback: async (action) => {
          if (action === 'confirm') {
            await functionListAuthorizationService.deleteFunctionById(row.id)
            this.resetFunctionList()
          }
        }
      })
    },
    // function auth maintenance
    onEditFunctionAuthSaveBtn() {
      let me = this
      this.$refs.editFunctionAuthDialogForm.validateForm().then(async (valid) => {
        if (valid) {
          let newFunctionAuth = this.$refs.editFunctionAuthDialogForm.getFunctionAuthEditModel()
          await functionListAuthorizationService.addFunctionAuth(newFunctionAuth).then(async () => {
            await me.getFunctionAuthorization(newFunctionAuth.functionId)
          })
          this.editFunctionAuthDialogVisible = false
        }
      })
    },
    onEditFunctionAuthCancelBtn() {
      this.editFunctionAuthDialogVisible = false
    },
    onAddFunctionAuthBtn() {
      this.editFunctionAuthDialogVisible = true
      let functionAuthModel = {
        functionName: this.currentFunctionObj.functionName,
        functionId: this.currentFunctionObj.id,
        statusSelectionList: [],
        rolesSelectionList: []
      }
      let baseInfo = {
        rolesList: this.rolesList,
        statusList: this.statusList,
        isRoleRelated: this.currentFunctionRoleRelated,
        isStatusRelated: this.currentFunctionStatusRelated
      }
      this.$nextTick(() => {
        this.$refs.editFunctionAuthDialogForm.setDataToFunctionAuthEditForm(functionAuthModel, baseInfo)
      })
    },
    handleDeleteFunctionAuthButton(index, row) {
      let me = this
      this.$confirm(`Are you sure you want to delete this record ?`, 'Warning', {
        dangerouslyUseHTMLString: true,
        confirmButtonText: 'Delete',
        cancelButtonText: 'Cancel',
        type: 'warning',
        callback: async (action) => {
          if (action === 'confirm') {
            await functionListAuthorizationService.deleteFunctionAuth(row.functionAuthId).then(async () => {
              await me.getFunctionAuthorization(row.functionId)
            })
          }
        }
      })
    },
    async getFunctionAuthorization(functionId) {
      this.functionAuthorizationTableData = await functionListAuthorizationService.getFunctionListAuth(functionId)
    },
    async getFunctionList(pageIndex) {
      let sortOrderList = []

      let sort = {
        property: 'functionName',
        direction: 'ASC'
      }
      sortOrderList.push(sort)
      let params = {
        page: pageIndex,
        start: 0,
        limit: this.functionPagable.limit,
        sortOrderList: sortOrderList
      }
      let result = await functionListAuthorizationService.getFunctionListWithPageParams(params)
      this.functionTableData = result.content
      this.functionPagable.totalElements = result.totalElements
      this.functionCurrentPage = pageIndex
    },
    async getOverAllStatus() {
      this.statusList = await statusService.getStatusByType(OVER_ALL)
    },
    async getAllRoles() {
      let sortOrderList = []
      let sort = {
        property: 'roleName',
        direction: 'ASC'
      }
      sortOrderList.push(sort)
      let params = {
        sortOrderList: sortOrderList
      }
      this.rolesList = await rolesService.getRoleAndAuthorization(params)
    }
  }
}
</script>

<style scoped lang="scss">
  @import './../../../common/css/base.scss';

  .add-button-class {
    margin-top: 10px;
    margin-left: 15px;
  }

  .pagination {
    align-items: center;
    margin-left: auto;
    margin-right: auto;
  }

  .panel-border {
    border: 1px solid $base-header-color;
  }

  .search-panel {
    height: 100px;
    margin: 10px;
    padding: 10px;
    border: 1px solid $base-header-color;
  }

  .table {
    margin: 15px;
  }

  .header-class {
    @include baseHeader(30px)
  }

  .header-text {
    color: #fff;
    padding-top: 5px;
    font-weight: bold;
  }

</style>
